package controller

import (
	"frontend-server/dao"
	"frontend-server/util"

	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

type ChatController struct{}

// 聊天记录列表
func (ChatController) ChatList(ctx *gin.Context) {
	roomID := ctx.Query("room_id")
	if roomID == "" {
		util.Success(ctx, util.R{
			P: util.P{
				Code:    -1,
				Message: "房间号不能为空",
			},
		})
		return
	}
	castUintRoomID, err := cast.ToUintE(roomID)
	if err != nil {
		util.Fail(ctx, util.R{
			P: util.P{
				Code:    500,
				Message: "房间 id 类型转换失败",
			},
		})
		return
	}
	// 判断用户是否属于该房间
	userID, _ := ctx.Get("id")
	castUintUserID, err := cast.ToUintE(userID)
	if err != nil {
		util.Fail(ctx, util.R{
			P: util.P{
				Code:    500,
				Message: "用户 id 类型转换失败",
			},
		})
		return
	}
	userRoom, err := dao.GetGvImUserRoomByUserIDRoomID(castUintUserID, castUintRoomID)
	if err != nil {
		util.Fail(ctx, util.R{
			P: util.P{
				Code:    500,
				Message: "非法访问",
			},
		})
		return
	}
	page, _ := cast.ToIntE(ctx.Query("page"))
	pageSize, _ := cast.ToIntE(ctx.Query("page_size"))
	skip := (page - 1) * pageSize
	// 聊天记录查询
	gim, err := dao.GetGvImMessageRListByRoomID(userRoom.RoomID, pageSize, skip)
	if err != nil {
		util.Fail(ctx, util.R{
			P: util.P{
				Code:    500,
				Message: "系统异常:" + err.Error(),
			},
		})
		return
	}
	util.Success(ctx, util.R{
		P: util.P{
			Code:    200,
			Message: "数据加载成功",
			Params: gin.H{
				"data": gim,
			},
		},
	})
}
